<template>
  <v-card class="elevation-0">
    <v-toolbar
      color="white"
      flat
    >
      <v-toolbar-title>
        注册
      </v-toolbar-title>
      <v-spacer />
      <v-tooltip bottom>
        <template v-slot:activator="{ on }">
          <v-btn color="secondary" depressed text v-on="on" @click="goLogin">
            <v-icon dark>mdi-login</v-icon>
          </v-btn>
        </template>
        <span>已有账号？快去登录</span>
      </v-tooltip>
    </v-toolbar>
    <v-card-text>
      <v-stepper
        v-model="e1"
        class="elevation-0"
        :vertical="vertical"
        :alt-labels="altLabels"
      >
        <!--步骤头-->
        <v-stepper-header>
          <template>
            <!--第一步-->
            <v-stepper-step
              step="1"
              :complete="e1 > 1"
            >
              用户信息
            </v-stepper-step>
            <v-divider />
            <!--第二步-->
            <v-stepper-step
              step="2"
              :complete="e1 > 2"
            >
              个人信息
            </v-stepper-step>
            <v-divider />
            <!--第三步-->
            <v-stepper-step
              step="3"
              :complete="e1 > 3"
            >
              个性化
            </v-stepper-step>
            <v-divider />

            <!--第四步-->
            <v-stepper-step
              step="4"
              :complete="e1 === 4"
            >
              Let's Go
            </v-stepper-step>
          </template>
        </v-stepper-header>

        <v-stepper-items>
          <ValidationObserver ref="userInfoObserver">
            <!--第一步的内容-->
            <v-stepper-content
              step="1"
            >
              <v-card color="white">
                <v-row>
                  <v-col>
                    <ValidationProvider
                      v-slot="{ errors }"
                      name="username"
                      rules="required|max:10"
                    >
                      <v-text-field
                        v-model="username"
                        :counter="10"
                        prepend-icon="mdi-account-box-outline"
                        :error-messages="errors"
                        placeholder="输入用来登录的用户名"
                        label="用户名"
                        solo
                      />
                    </ValidationProvider>
                  </v-col>
                  <v-col>
                    <ValidationProvider
                      v-slot="{ errors }"
                      name="name"
                      rules="required|max:12"
                    >
                      <v-text-field
                        v-model="name"
                        :counter="12"
                        prepend-icon="mdi-music-box-outline"
                        :error-messages="errors"
                        placeholder="取个昵称吧"
                        label="昵称"
                        solo
                      />
                    </ValidationProvider>
                  </v-col>
                </v-row>
                <v-row>
                  <v-col>
                    <ValidationProvider
                      v-slot="{ errors }"
                      name="password"
                      rules="required|max:18|min:6"
                    >
                      <v-text-field
                        ref="password"
                        v-model="password"
                        :counter="18"
                        type="password"
                        prepend-icon="mdi-textbox-password"
                        :error-messages="errors"
                        placeholder="请输入密码"
                        label="密码"
                        solo
                      />
                    </ValidationProvider>
                  </v-col>
                  <v-col>
                    <ValidationProvider
                      v-slot="{ errors }"
                      name="repassword"
                      rules="required|max:18|min:6|confirmed:password"
                    >
                      <v-text-field
                        v-model="repassword"
                        :counter="18"
                        type="password"
                        prepend-icon="mdi-ticket-confirmation-outline"
                        :error-messages="errors"
                        placeholder="请重复输入密码"
                        name="password_confirmation"
                        label="确认密码"
                        solo
                      />
                    </ValidationProvider>
                  </v-col>
                </v-row>
                <v-row justify="center">
                  <v-btn color="blue lighten-3" dark class="mr-3" @click="previousStep(1)">
                    上一步
                  </v-btn>
                  <v-btn color="primary" @click="nextStep(1)">
                    下一步
                  </v-btn>
                  <v-btn class="ml-3" color="green darken-1" dark @click="resetUserInfo">重置</v-btn>
                </v-row>
              </v-card>
            </v-stepper-content>
          </ValidationObserver>
          <!--第二步的内容-->
          <ValidationObserver ref="personalObserver">
            <v-stepper-content step="2">
              <v-card color="white">
                <v-row>
                  <v-col>
                    <ValidationProvider
                      v-slot="{ errors }"
                      name="phone"
                      rules="required|max:11|phone"
                    >
                      <v-text-field
                        v-model="phone"
                        :counter="11"
                        prepend-icon="mdi-card-account-phone-outline"
                        :error-messages="errors"
                        placeholder="输入您的电话"
                        label="电话"
                        solo
                      />
                    </ValidationProvider>
                  </v-col>
                  <v-col>
                    <ValidationProvider
                      v-slot="{ errors }"
                      name="address"
                      rules="required|max:256"
                    >
                      <v-text-field
                        v-model="address"
                        :counter="256"
                        prepend-icon="mdi-home"
                        :error-messages="errors"
                        placeholder="输入您的地址"
                        label="地址"
                        solo
                      />
                    </ValidationProvider>
                  </v-col>
                </v-row>
                <v-row>
                  <v-col>
                    <ValidationProvider v-slot="{ errors }" name="sex" rules="required">
                      <v-select
                        v-model="sex"
                        prepend-icon="mdi-gender-transgender"
                        :items="sexs"
                        solo
                        :error-messages="errors"
                        label="性别"
                      />
                    </ValidationProvider>
                  </v-col>
                  <v-col>
                    <ValidationProvider
                      v-slot="{ errors }"
                      name="age"
                      rules="required|max:3|integer"
                    >
                      <v-text-field
                        v-model="age"
                        :counter="3"
                        prepend-icon="mdi-numeric"
                        :error-messages="errors"
                        placeholder="输入您的年龄"
                        label="年龄"
                        solo
                      />
                    </ValidationProvider>
                  </v-col>
                </v-row>

                <v-btn color="blue lighten-3" dark class="mr-3" @click="previousStep(2)">
                  上一步
                </v-btn>
                <v-btn color="primary" @click="nextStep(2)">
                  下一步
                </v-btn>
                <v-btn class="ml-3" color="green darken-1" dark @click="resetPersonal">重置</v-btn>
              </v-card>
            </v-stepper-content>
          </ValidationObserver>
          <!--第三步的内容-->
          <ValidationObserver ref="specialObserver">
            <v-stepper-content step="3">
              <v-card color="white">
                <v-row justify="center">
                  <v-col v-show="!uploaded">
                    <v-text-field
                      id="pick-avatar"
                      readonly
                      placeholder="建议您给自己先选个头像"
                      prepend-icon="mdi-camera"
                      label="头像"
                    />
                    <avatar-cropper
                      trigger="#pick-avatar"
                      upload-form-name="image"
                      upload-url="/api/file/fastDFSUpload"
                      @uploaded="handleUploaded"
                      @uploading="handleUploading"
                      @completed="handleCompleted"
                      @error="handlerError"
                    />
                  </v-col>
                  <v-col v-show="uploaded">
                    <v-row>
                      <v-col cols="3" align-self="center" class="subtitle-1">
                        您的头像：
                      </v-col>
                      <v-col cols="9" class="avatar-register">
                        <v-avatar
                          class="user-avatar"
                          tile="tile"
                          :size="size"
                        >
                          <img
                            :src="avatarFinal"
                            alt="头像"
                          >
                        </v-avatar>
                      </v-col>
                    </v-row>
                  </v-col>
                </v-row>

                <v-row justify="center">
                  <v-col>
                    <ValidationProvider
                      v-slot="{ errors }"
                      name="signature"
                      rules="required|max:120"
                    >
                      <v-textarea
                        v-model="signature"
                        clearable
                        filled
                        rounded
                        outlined
                        :error-messages="errors"
                        label="个性签名"
                        :value="signature"
                      />
                    </ValidationProvider>
                  </v-col>
                </v-row>
                <v-row justify="center">
                  <v-btn color="blue lighten-3" dark class="mr-3" @click="previousStep(3)">
                    上一步
                  </v-btn>
                  <v-btn color="primary" @click="nextStep(3)">
                    下一步
                  </v-btn>
                  <v-btn class="ml-3" color="green darken-1" dark @click="resetSpecialInfo">重置</v-btn>
                </v-row>
              </v-card>
            </v-stepper-content>
          </ValidationObserver>
          <!--第四步的内容-->
          <v-stepper-content step="4">
            <v-card color="white">
              <v-row justify="center">
                伞兵一号 <span
                  style="margin: 0 15px;font-size: 18px;font-weight: bold;color: cornflowerblue"
                >{{ name || "???" }}</span>
                准备就绪!!! ~
              </v-row>
              <v-row class="mt-6" justify="center">
                <v-btn color="blue lighten-3" dark class="mr-3" @click="previousStep(4)">
                  上一步
                </v-btn>
                <v-btn
                  dark
                  color="green darken-3"
                  @click="register"
                >
                  注册
                </v-btn>

              </v-row>

            </v-card>

          </v-stepper-content>
        </v-stepper-items>
      </v-stepper>

    </v-card-text>
  </v-card>

</template>

<script>
import '@/assets/css/login/register.scss'
import { required, min, max, confirmed, integer } from 'vee-validate/dist/rules'
import { registerUser } from '@/api/user'
import { extend, ValidationObserver, ValidationProvider, setInteractionMode } from 'vee-validate'
import AvatarCropper from 'vue-avatar-cropper'

const Base64 = require('js-base64').Base64

setInteractionMode('eager')

extend('phone', {
  messages: '{_field_} 格式不正确',
  validate: value => {
    return /^1([34578])\d{9}$/.test(value)
  }
})
extend('required', {
  ...required,
  message: '{_field_} 不能为空'
})

extend('max', {
  ...max,
  message: '{_field_} 不超过 {length} 个字符'
})

extend('min', {
  ...min,
  message: '{_field_} 不少于 {length} 个字符'
})

extend('integer', {
  ...integer,
  message: '{_field_} 必须是整数'
})

extend('confirmed', {
  ...confirmed,
  message: '两次输入密码必须相同'
})

export default {
  name: 'RegisterPage',
  components: {
    ValidationProvider,
    ValidationObserver,
    AvatarCropper
  },
  // 注册步骤条
  data: () => ({
    e1: 1,
    steps: 4,
    vertical: false,
    altLabels: false,
    // editable: true,
    sexs: [
      '男', '女', '保密'
    ],
    uploaded: false,
    size: 100,
    // 注册表单-用户信息
    username: '',
    name: '',
    password: '',
    repassword: '',
    // 个人信息
    phone: '',
    address: '',
    sex: '',
    age: '',
    // 个性化信息
    avatar: '',
    signature: ''
  }),
  computed: {
    avatarFinal() {
      return this.avatar === '' ? 'http://119.23.10.3:8018/group1/M00/00/00/rBIUS1-BXsOAeA1jAAAhIDW5dXQ408.jpg' : this.avatar
    }
  },
  watch: {
    steps(val) {
      if (this.e1 > val) {
        this.e1 = val
      }
    },
    vertical() {
      this.e1 = 2
      requestAnimationFrame(() => this.e1 = 1) // Workarounds
    }
  },
  methods: {
    handleUploading(form, xhr) {
      // console.log("正在上传中...");
    },
    handleUploaded(res, form, xhr) {
      if (res.code === 200) {
        this.avatar = res.data
        this.uploaded = true
      } else {
        this.$iziToast.error({ message: res.msg })
      }
    },
    handleCompleted(res, form, xhr) {
      // console.log("上传完成，返回结果为..." + res)
    },
    handlerError(message, type, xhr) {
      if (type === 'upload') {
        console.error(message)
      }
    },
    register() {
      const that = this
      const params = {
        username: this.username,
        name: this.name,
        password: Base64.encode(this.password),
        phone: this.phone,
        address: this.address,
        sex: this.sex,
        age: this.age,
        avatar: this.avatar,
        signature: this.signature
      }
      registerUser(params)
        .then((res) => {
          if (res && res.code === 200) {
            // 提示注册成功
            this.$iziToast.question({
              message: '注册成功! 系统将在5秒后跳转至登录界面',
              timeout: 5000,
              overlay: true,
              pauseOnHover: false,
              position: 'center',
              zindex: 999,
              displayMode: 'once',
              onClosed: function(instance, toast, closedBy) {
                console.info('Closed | closedBy: ' + closedBy)
                that.goLogin()
              }
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
        .finally(() => {
          console.log('注册流程结束啦......')
        })
    },
    nextStep(n) {
      const that = this
      if (n === this.steps) {
        this.e1 = 1
      } else {
        // 判断当前校验是否通过，不通过则不允许进行下一步
        switch (n) {
          case 1:
            // 用户信息
            that.$refs.userInfoObserver.validate().then(result => {
              if (result) {
                // 进入下一步
                this.e1 = n + 1
              } else {
                this.$iziToast.error({ message: '抱歉，校验不通过，请先保证用户信息合格~' })
              }
            })
            break
          case 2:
            that.$refs.personalObserver.validate().then(result => {
              if (result) {
                // 进入下一步
                this.e1 = n + 1
              } else {
                this.$iziToast.error({ message: '抱歉，校验不通过，请先保证个人信息合格~' })
              }
            })
            // 个人信息
            break
          case 3:
            // 个性化信息
            that.$refs.specialObserver.validate().then(result => {
              if (result) {
                // 进入下一步
                this.e1 = n + 1
              } else {
                this.$iziToast.error({ message: '抱歉，校验不通过，请先保证个性化信息合格~' })
              }
            })
            break
          default:
            // 4 或者其他啥也不做;
            console.log('你已经准备好了吧!')
            break
        }
      }
    },
    previousStep(n) {
      if (n !== 1) {
        this.e1 = n - 1
      } else {
        this.$iziToast.question({ message: '已经是第一步了,您想干啥?' })
      }
    },
    goLogin() {
      this.clear()
      this.$emit('goLoginForm')
    },
    resetUserInfo() {
      this.name = ''
      this.username = ''
      this.password = ''
      this.repassword = ''
      this.$refs.userInfoObserver.reset()
    },
    resetPersonal() {
      this.phone = ''
      this.address = ''
      this.sex = ''
      this.age = ''
      this.$refs.personalObserver.reset()
    },
    resetSpecialInfo() {
      this.avatar = ''
      this.signature = ''
      this.$refs.specialObserver.reset()
    },
    clear() {
      this.e1 = 1
      this.uploaded = false
      // 清理所有
      this.resetUserInfo()
      this.resetPersonal()
      this.resetSpecialInfo()
    }
  }

}
</script>
